﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BasePlatformNet;
using System.Threading;
using BasePlatformCommon;

namespace L9SubSet
{
	public partial class Form_FixSubPos : Form
	{
		private BaseCoreNet baseCoreNet = null;	// 底层通信平台引用（单例）

		private int startSubPos = -1;

		private bool pauseFlag = false;
		private bool forceExitFlag = false;

		private int subIP1 = 192;
		private int subIP2 = 168;
		private int subIP3 = 1;

		// 委托定义与声明
		public delegate void UpdateProgressDelegate(int currentNum, int totalNum);
		public UpdateProgressDelegate updateProgressDelegate;

		private string section = "FixSubPos";			// 多语言文件配置节名称

		private string tip = "提示";						// MessageBox 题头

		/*****************************************************************************************/

		// 构造函数
		public Form_FixSubPos(BaseCoreNet baseCoreNet)
		{
			InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			this.baseCoreNet = baseCoreNet;
			updateProgressDelegate = new UpdateProgressDelegate(updateProgress);

			ip1TextBox.Text = "192";
			ip2TextBox.Text = "168";
			ip3TextBox.Text = "1";

			ip1TextBox.Enabled = false;
			ip2TextBox.Enabled = false;
			ip3TextBox.Enabled = false;
			ipLabe1.Enabled = false;
			ipLabe2.Enabled = false;
			ipLabe3.Enabled = false;
			ipLabe4.Enabled = false;

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}
		}

		// 设置本地化语言
		public void setLanguageText()
		{
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "fixSubPos.Text");
			startSubLabel.Text = LanguageOper.ReadValue(section, "startSubLabel.Text");
			fixAllSubCheckBox.Text = LanguageOper.ReadValue(section, "fixAllSubCheckBox.Text");
			configArtNetCheckBox.Text = LanguageOper.ReadValue(section, "configArtNetCheckBox.Text");
			ipLabe1.Text = LanguageOper.ReadValue(section, "ipLabe1.Text");
			processLabel.Text = LanguageOper.ReadValue(section, "processLabel.Text");
			applyButton.Text = LanguageOper.ReadValue(section, "applyButton.Text");
			testButton.Text = LanguageOper.ReadValue(section, "testButton.Text");
			exitButton.Text = LanguageOper.ReadValue(section, "exitButton.Text");
		}

		// 检查输入参数
		private bool checkInputParameter()
		{
			int tmpStartSubPos = -1;
			bool res = int.TryParse(startPosTextBox.Text.Trim(), out tmpStartSubPos);
			if (res == false || tmpStartSubPos < 1 || tmpStartSubPos > 254)
			{
				string msg = "起始分控编号输入错误：应在 [1,254] 范围";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.0");
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
				
				return false;
			}
			else
			{
				startSubPos = tmpStartSubPos;
			}

			int totalSubNum = baseCoreNet.getSubControlNum();
			if (startSubPos + totalSubNum > 254)
			{
				string msg = string.Format("当前有 {0} 个分控, 固化地址范围（{1}+{2}）超过254", totalSubNum, startSubPos, totalSubNum);
				if (LanguageOper.available == true)
				{
					msg = string.Format(LanguageOper.ReadValue(section, "msgStr.1"), totalSubNum, startSubPos, totalSubNum);
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
				
				return false;
			}

			// 配置 artnet 网段参数
			if (configArtNetCheckBox.Checked)
			{
				int tmpSubIP = -1;
				
				res = int.TryParse(ip1TextBox.Text.Trim(), out tmpSubIP);
				if (res == false || tmpSubIP < 0 || tmpSubIP > 255)
				{
					string msg = "IP 段 1 输入错误：应在 [0,255] 范围";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.2");
					}

					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
					
					return false;
				}
				else
				{
					subIP1 = tmpSubIP;
				}

				res = int.TryParse(ip2TextBox.Text.Trim(), out tmpSubIP);
				if (res == false || tmpSubIP < 0 || tmpSubIP > 255)
				{
					string msg = "IP 段 2 输入错误：应在 [0,255] 范围";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.3");
					}
					
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
					
					return false;
				}
				else
				{
					subIP2 = tmpSubIP;
				}

				res = int.TryParse(ip3TextBox.Text.Trim(), out tmpSubIP);
				if (res == false || tmpSubIP < 0 || tmpSubIP > 255)
				{
					string msg = "IP 段 3 输入错误：应在 [0,255] 范围";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.4");
					}
					
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
					
					return false;
				}
				else
				{
					subIP3 = tmpSubIP;
				}
			}

			return true;
		}

		// 配置 artnet 网段
		private void configArtNetCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			ip1TextBox.Enabled = configArtNetCheckBox.Checked;
			ip2TextBox.Enabled = configArtNetCheckBox.Checked;
			ip3TextBox.Enabled = configArtNetCheckBox.Checked;
			ipLabe1.Enabled = configArtNetCheckBox.Checked;
			ipLabe2.Enabled = configArtNetCheckBox.Checked;
			ipLabe3.Enabled = configArtNetCheckBox.Checked;
			ipLabe4.Enabled = configArtNetCheckBox.Checked;
		}

		// 应用
		private void applyButton_Click(object sender, EventArgs e)
		{
			int totalSubNum = baseCoreNet.getSubControlNum();
			if (totalSubNum == 0)
			{
				string msg = "当前未检测到分控";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.5");
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);
				
				return;
			}

			if (checkInputParameter() == false)
			{
				return;
			}

			bool fixAllSub = fixAllSubCheckBox.Checked;
			bool artNetEnable = configArtNetCheckBox.Checked;
			Thread t = new Thread(() =>
			{
				// 硬件配置操作前处理
				baseCoreNet.configPreTreat();

				// 主逻辑操作
				fixSubPositionHandle("apply", fixAllSub, artNetEnable, subIP1, subIP2, subIP3);

				// 硬件配置操作后处理
				baseCoreNet.configPostTreat();
			});
			t.IsBackground = true;
			t.Start();
		}

		// 测试
		private void testButton_Click(object sender, EventArgs e)
		{
			int totalSubNum = baseCoreNet.getSubControlNum();
			if (totalSubNum == 0)
			{
				string msg = "当前未检测到分控";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.5");
				}

				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);

				return;
			}

			if (checkInputParameter() == false)
			{
				return;
			}

			bool fixAllSub = fixAllSubCheckBox.Checked;
			bool artNetEnable = configArtNetCheckBox.Checked;
			Thread t = new Thread(() =>
			{
				// 硬件配置操作前处理
				baseCoreNet.configPreTreat();

				// 主逻辑操作
				fixSubPositionHandle("test", fixAllSub, artNetEnable, subIP1, subIP2, subIP3);

				// 硬件配置操作后处理
				baseCoreNet.configPostTreat();
			});
			t.IsBackground = true;
			t.Start();
		}

		// 退出
		private void exitButton_Click(object sender, EventArgs e)
		{
			if (applyButton.Enabled == false)
			{
				pauseFlag = true;

				string msg = "分控位置固化操作正在进行，仍要退出吗？";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.6");
				}

				DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OKCancel, MessageBoxIcon.None);
				
				if (dr == System.Windows.Forms.DialogResult.OK)
				{
					forceExitFlag = true;
					this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
				}
				else
				{
					pauseFlag = false;
				}
			}
			else
			{
				this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			}
		}

		// 实际逻辑动作
		private void fixSubPositionHandle(string mode, bool fixAllSub, bool artNetEnable, int ip1, int ip2, int ip3)
		{
			if (baseCoreNet == null)
			{
				return;
			}

			forceExitFlag = false;
			pauseFlag = false;

			int totalSubNum = baseCoreNet.getSubControlNum();
			int devIndex = baseCoreNet.getActiveDevIndex();

			// 清除分控序号，直接将 0x0200 地址写入全0（不用擦除）
			byte[] dataClear = new byte[256];
			for (int i = 0; i < 256; i++)
			{
				dataClear[i] = 0;
			}

			// 勾选 "固化所有分控"
			if (fixAllSub == true)
			{
				this.Invoke(updateProgressDelegate, 0, totalSubNum);

				// 先写入 0x4c0200，再写入 0x0200, 全局写
				baseCoreNet.writeSubMem(devIndex, 0, 0x4c0200, dataClear, true);
                Thread.Sleep(10);
                baseCoreNet.writeSubMem(devIndex, 0, 0x0200, dataClear, true);

				// 从最后一个分控向前写，防止中间出现序号重复
				for (int subIndex = totalSubNum; subIndex > 0; subIndex--)
				{
					if (forceExitFlag == true)
					{
						break;
					}

					while (pauseFlag == true)
					{
						Thread.Sleep(200);
						continue;
					}

					// 从 0x4c0100 地址读回512字节，实际的编号地址为 0x4c0209 和 0x4c020a
					byte[] data = baseCoreNet.readFirmware(devIndex, subIndex, 0x4c0100, 512, false);
					data[0x109] = (byte)(subIndex + startSubPos - 1);
					data[0x10a] = 0x3c;

					// artNet
					if (artNetEnable == true)
					{
						data[0x110] = 0x3c;
						data[0x111] = (byte)ip1;
						data[0x112] = (byte)ip2;
						data[0x113] = (byte)ip3;
					}
					else
					{
						data[0x110] = 0xff;
					}

					// 写回Flash
					baseCoreNet.write2Flash(devIndex, subIndex, data, 0x5c0100, 0x4c0100, 512, false);

					// 修改 0x0200 地址的sram
					byte[] ddd = new byte[256];
					for (int i = 0; i < 256; i++)
					{
						ddd[i] = data[i + 256];
					}

					baseCoreNet.writeSubMem(devIndex, subIndex, 0x0200, ddd, false);

					if (this != null && this.Visible == true)
					{
						this.Invoke(updateProgressDelegate, totalSubNum - subIndex + 1, totalSubNum);
					}
				}
			}
			// 不勾选 "固化所有分控"，仅对首分控固化，并且将 0x4c020b 和 0x020b 字节也设置为0x3C
			else
			{
				this.Invoke(updateProgressDelegate, 0, 1);

				int subIndex = 1;

				// 对首分控先写入 0x4c0200，再写入 0x0200, 定点写
				baseCoreNet.writeSubMem(devIndex, subIndex, 0x4c0200, dataClear, true);
                Thread.Sleep(10);
                baseCoreNet.writeSubMem(devIndex, subIndex, 0x0200, dataClear, true);

				// 从 0x4c0100 地址读回512字节，实际的编号地址为 0x4c0209 和 0x4c020a
				byte[] data = baseCoreNet.readFirmware(devIndex, subIndex, 0x4c0100, 512, false);
				data[0x109] = (byte)(subIndex + startSubPos - 1);
				data[0x10a] = 0x3c;
				data[0x10b] = 0x3c;

				// artNet
				if (artNetEnable == true)
				{
					data[0x110] = 0x3c;
					data[0x111] = (byte)ip1;
					data[0x112] = (byte)ip2;
					data[0x113] = (byte)ip3;
				}
				else
				{
					data[0x110] = 0xff;
				}

				// 写回Flash
				baseCoreNet.write2Flash(devIndex, subIndex, data, 0x5c0100, 0x4c0100, 512, false);

				// 修改 0x0200 地址的sram
				byte[] ddd = new byte[256];
				for (int i = 0; i < 256; i++)
				{
					ddd[i] = data[i + 256];
				}

				baseCoreNet.writeSubMem(devIndex, subIndex, 0x0200, ddd, false);

				if (this != null && this.Visible == true)
				{
					this.Invoke(updateProgressDelegate, 1, 1);
				}
			}
		}

		// 更新操作进度
		private void updateProgress(int currentNum, int totalNum)
		{
			if (totalNum == 0)
			{
				return;
			}

			int value = currentNum * 100 / totalNum;
			if (value < 0 || value > 100)
			{
				return;
			}

			fixProgressBar.Value = value;
			fixProgressLabel.Text = currentNum + " / " + totalNum;

			if (value == 0)
			{
				applyButton.Enabled = false;
			}
			else if (value == 100)
			{
				applyButton.Enabled = true;

				string msg = "分控序号固化完成";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.7");
				}

				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.None);

				fixProgressBar.Value = 0;
				fixProgressLabel.Text = "0 / 0";
			}
		}

		// 窗体关闭前处理
		private void Form_FixSubPos_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (applyButton.Enabled == false)
			{
				pauseFlag = true;

				string msg = "分控位置固化操作正在进行，仍要退出吗？";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.6");
				}

				DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OKCancel, MessageBoxIcon.None);
				
				if (dr == System.Windows.Forms.DialogResult.OK)
				{
					forceExitFlag = true;
					this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
				}
				else
				{
					pauseFlag = false;
					e.Cancel = true;
				}
			}
			else
			{
				this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			}
		}

	}
}
